package com.ksp.wke.kspa04;

import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.factory.annotation.Autowired;

public class OrderDealThread implements Runnable{

	ConcurrentLinkedQueue<OrderRequest> orderQueue;

    private static AtomicInteger totalprodocut;

    public static ReentrantLock dealLock = new ReentrantLock(true);

    static {
        totalprodocut = new AtomicInteger(15);
    }

    public OrderDealThread() {
    }
    

    public OrderDealThread(ConcurrentLinkedQueue<OrderRequest> queque) {
        this.orderQueue = queque;
    }
	
	
	@Override
	public void run() {
		while (!orderQueue.isEmpty()) {
            try {
                dealLock.lock();
                //使用迭代器遍历orderQueue
                Iterator<OrderRequest> it = orderQueue.iterator();
                while (it.hasNext()) {
                    dealQueque(it.next());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                dealLock.unlock();
            }
        }
		
	}
	
	 void dealQueque(OrderRequest orderRequest) {
	        if (orderRequest.getStatus() == 0) {
	            int status = 2;
	            if (totalprodocut.get() > 0) {//需再次判断是否还有商品，加锁范围内
	                totalprodocut.decrementAndGet();// 减库存
	                status =1;
	            }

	            if (status == 2) {
	                System.out.println(orderRequest.getUserId() + " deal er:" + Thread.currentThread().getName());
	                orderRequest.setStatus(2);
	            } else {
	                System.out.println(orderRequest.getUserId() + " deal ok:" + Thread.currentThread().getName());
	                orderRequest.setStatus(1);
	            }
	        }
	    }

}
